package com.smasher.dialog.select.adapter

import android.util.SparseIntArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.util.size
import com.smasher.dialog.R
import com.smasher.dialog.select.delegate.ElementShowDelegate
import com.smasher.dialog.select.delegate.SelectDelegate
import com.smasher.dialog.select.SelectMode
import com.smasher.widget.base.BaseRecyclerAdapter

open class SelectAdapter<T>(
    private var elementShowDelegate: ElementShowDelegate<T>
) : BaseRecyclerAdapter<T, SelectViewHolder<T>>() {

    var mode: SelectMode = SelectMode.SINGLE
        set(value) {
            field = value
            delegate.mode = value
        }

    private var delegate = object : SelectDelegate(mode) {
        override fun notifyAdapterItemChanged(sparseIntArray: SparseIntArray) {
            for (i in 0 until sparseIntArray.size) {
                val index = sparseIntArray.keyAt(i)
                notifyItemChanged(index)
            }

        }
    }

    override fun onCreateDefineViewHolder(viewGroup: ViewGroup, i: Int): SelectViewHolder<T> {
        val view = getView(viewGroup)
        return SelectViewHolder(view)
    }

    override fun onBindViewHolderPre(viewHolder: SelectViewHolder<T>, position: Int) {
        viewHolder.setElementShowDelegate(elementShowDelegate)
        viewHolder.setSelected(delegate.isSelected(position))
        viewHolder.setOnSingleSelectListener(delegate)
    }

    open fun getView(viewGroup: ViewGroup): View {
        val inflater = LayoutInflater.from(viewGroup.context)
        return inflater.inflate(R.layout.item_select_base, viewGroup, false)
    }


    fun getSelectList(): ArrayList<T> {
        val selectedArray = delegate.selectedArray
        val selectList = ArrayList<T>()
        for (i in 0 until selectedArray.size) {
            val index = selectedArray.keyAt(i)
            val item = getItem(index)
            if (item != null) {
                selectList.add(item)
            }
        }
        return selectList
    }
}